﻿using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.DirectoryServices;
using System.IO;
using System.Xml;
using Orbitone.MeetingRooms.Services.Model;

namespace Orbitone.MeetingRooms.Services
{
    public class LdapService
    {
        private DirectoryEntry _directoryEntry;

        public LdapService()
        {
            var username = ConfigurationManager.AppSettings["username"];
            var password = ConfigurationManager.AppSettings["password"];
            var domain = ConfigurationManager.AppSettings["domain"];
            var ldapserver = ConfigurationManager.AppSettings["ldapserver"];

            _directoryEntry = new DirectoryEntry(ldapserver, domain + "\\" + username, password);
        }

        public List<MailboxModel> FindRooms()
        {
            return FindMailboxes(ConfigurationManager.AppSettings["find_rooms"]);
        }

        private List<MailboxModel> FindMailboxes(string sqSearchQuery)
        {
            var dsDirectorySearcher = new DirectorySearcher(_directoryEntry);
            dsDirectorySearcher.SearchScope = SearchScope.Subtree;
            dsDirectorySearcher.Filter = sqSearchQuery;
            var srSearchResults = dsDirectorySearcher.FindAll();

            var mailboxes = new List<MailboxModel>();
            foreach (SearchResult srSearchResult in srSearchResults)
            {
                var model = new MailboxModel();
                model.EmailAddress = srSearchResult.Properties["mail"][0].ToString();
                model.DisplayName = srSearchResult.Properties["displayName"][0].ToString();
                mailboxes.Add(model);
            }

            return mailboxes;
        }
    }
}